import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/AppConfig/Config.dart';
import 'package:sph_shipper/Order/EvaluationPage.dart';
import 'package:sph_shipper/Order/WaybillDetails/WaybillDetailsView.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../http/api.dart';
import 'package:platform/platform.dart';
class FreightPaymentSuccessful extends StatefulWidget {
  const FreightPaymentSuccessful({super.key, required this.dataMap});
  final Map dataMap;
  @override
  State<FreightPaymentSuccessful> createState() => _FreightPaymentSuccessfulState();
}

class _FreightPaymentSuccessfulState extends State<FreightPaymentSuccessful> {
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  //添加熟车
  void addMyDrivertAction(String drvId)async{
    String? token = await TokenManager.getToken();
    String? shipperId =await UserIdManager.getUserID();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler)  {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header+'api/user/shpr/familiardrv/add',
      data: {
        "shipperId": shipperId,
        "drvId":drvId,
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 5),
      ),

    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          BrnToast.show(
            "添加成功",
            context,
            duration: BrnDuration.short,
          );
        }else{
          BrnToast.show(
            jsonMap['msg'].toString(),
            context,
            duration: BrnDuration.short,
          );
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
    backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        title: Text("运费支付成功",style: TextStyle(fontWeight: FontWeight.w300,fontSize: 16.sp),),
        centerTitle: true,
        backgroundColor: Colors.white,
      ),
      body: ListView(children: [
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(left: 20.w,top: 17.h,bottom: 16.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Row(
            children: [
              Icon(Icons.check_circle,color: Color.fromRGBO(116, 203, 135, 1),size: 30,),
              SizedBox(width: 7.w,),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("支付成功",style: TextStyle(color: Colors.black),),
                  Text("运费已支付至司机，请注意保留交易证据",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                ],
              ),
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(right: 6.w,bottom: 3.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              BrnTagCustom(
                textPadding:EdgeInsets.only(left:12.w,right: 12.w ),
                fontSize: 12.sp,
                tagText: '司机',
                backgroundColor:MyColors.themeColor,
                tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10)),
              ),
              SizedBox(height: 4.h,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      SizedBox(width: 12.w,),
                      Image.network( "https://t12.baidu.com/it/u=2009860844,206760771&fm=30&app=106&f=JPEG?w=640&h=426&s=41313C722D374B925CF3F3D30300D0A9",
                        width: 36.w,height: 36.h,fit: BoxFit.cover,),
                      SizedBox(width:13.w ,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text("司机姓名",style: TextStyle(color: Colors.black),),
                          SizedBox(height: 3.h,),
                          Text("19966669999",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        ],
                      ),
                    ],
                    
                  ),
                  Row(
                    children: [
                      GestureDetector(
                        child: Image.asset("lib/Images/OrderList/IMicon.png",width:24.w ,height: 24.h,),
                        onTap: (){},
                      ),
                      SizedBox(width: 8.w,),
                      GestureDetector(
                        child: Image.asset("lib/Images/OrderList/电话联系icon.png",width:24.w ,height: 24.h,),
                        onTap: (){
                          _makePhoneCall('1234567890');
                        },
                      ),
                    ],
                  )
                ],
              )
            ],
          ),
            ),
        Container(
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.only(top: 20.w,bottom: 17.h),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(),
              GestureDetector(
                child:  Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付成功查看运单.png",width: 40.w,height: 40.h,),
                    SizedBox(height: 8.h,),
                    Text("查看运单",style: TextStyle(color: Colors.black),),
                  ],
                ),
                onTap: () async {
                  String? token =await TokenManager.getToken();
                  dio.interceptors.add(InterceptorsWrapper(
                      onRequest: (options, handler) {
                        options.headers["satoken"] = token;
                        return handler.next(options);
                      }
                  ));
                  dio
                      .post(
                    MyServiceUrl.header+'api/waybill/waybill/common/getWaybillDetail',
                    data: {
                      "waybillId": "",
                    },
                    options: Options(
                      sendTimeout: Duration(seconds: 2),
                      receiveTimeout: Duration(seconds: 5),
                    ),
                    onSendProgress: (a, b) => print('send ${a / b}'),
                    onReceiveProgress: (a, b) =>
                        print('received ${a / b}'),
                  )
                      .then((r) {
                    setState(() {
                      print(r);
                      Map<String, dynamic> jsonMap = json.decode(
                          r.toString());
                      // 获取code和data
                      String code = jsonMap['code'].toString();
                      if (code == "200") {
                        Navigator.push( context, FadeRoute(page:WaybillDetails(billId: jsonMap['data']['waybillId'],)));

                      }else {
                        BrnToast.show(
                          jsonMap['msg'],
                          context,
                          duration: BrnDuration.short,
                        );
                      }
                    });
                  }).catchError((error) {
                    print(error);
                    ;
                  });
                },
              ),

              GestureDetector(
                child: Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付成功评价司机.png",width: 40.w,height: 40.h,),
                    SizedBox(height: 8.h,),
                    Text("评价司机",style: TextStyle(color: Colors.black),),
                  ],
                ),
                onTap: (){
                  Navigator.push( context, FadeRoute(page:EvaluationPage(dataMap: {},)));
                },
              ),
              GestureDetector(
                child:  Column(
                  children: [
                    Image.asset("lib/Images/OrderList/支付成功添加熟车.png",width: 40.w,height: 40.h,),
                    SizedBox(height: 8.h,),
                    Text("添加熟车",style: TextStyle(color: Colors.black),),
                  ],
                ),
                onTap: (){
                  addMyDrivertAction("2");
                },
              ),

              SizedBox(),
            ],
          ),
            ),
      ],
      ),
    );
  }
}
